/**
 * @description: 用户信息全局变量
 * @Author: huangpeng
 * @Date: 2023年05月14日 18:14
 * @Copyright:  2022-2023
 */
import { login, logout, getInfo, refreshToken } from '@/api/auth/login'
import {
  getToken,
  setToken,
  setExpiresIn,
  removeToken,
  setUserId,
  removeUserId,
  removeUsername
} from "@/utils/auth";

const user = {
  state: {
    token: getToken(),
    roles: [],
    permissions: [],
    userInfo: {
      id: '',
      userCode: '',
      userName: '',
      gender: '',
      avatar: '',
      nickName: '',
      birthday: '',
      email: '',
      phone: '',
      qqNumber: '',
      weChat: '',
      summary: '',
      signature:'',
      oprationSystem: '',
      startEmailNotification: '',
      occupation: '',
      backUrl: ''
    },
	  thirdBindStatus: false
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
	  SET_THIRD_BIND_STATUS: (state, thirdBindStatus) => {
		  state.thirdBindStatus = thirdBindStatus;
	  },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          let data = res.data
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          setExpiresIn(data.expires_in)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const user = JSON.parse(JSON.stringify(res.user))
          const avatar = (user.avatar === "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : user.avatar;
          user['avatar'] = avatar;
          user['token'] = getToken();
          setUserId(user.id);
          commit('SET_USER_INFO', user);
          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          resolve(user);
        }).catch(error => {
          reject(error);
        })
      })
    },

    // 刷新token
    RefreshToken({commit, state}) {
      return new Promise((resolve, reject) => {
        refreshToken(state.token).then(res => {
          setExpiresIn(res.data)
          commit('SET_EXPIRES_IN', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
	        commit('SET_USER_INFO', {
		        id: '',
		        userCode: '',
		        userName: '',
		        gender: '',
		        avatar: '',
		        nickName: '',
		        birthday: '',
		        email: '',
		        phone: '',
		        qqNumber: '',
		        weChat: '',
		        summary: '',
		        signature:'',
		        oprationSystem: '',
		        startEmailNotification: '',
		        occupation: '',
		        backUrl: ''
	        });
          removeToken()
          removeUserId()
          removeUsername()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
